package cn.itcast.n8;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

/**
 * @author: AirMan
 * @date: 2025/4/22 18:38
 * @description:
 */

@Slf4j(topic = "c.TestForkJoin_My2")
public class TestForkJoin_My2 {
    public static void main(String[] args) {

        ForkJoinPool pool = new ForkJoinPool(1000);

        Integer result = pool.invoke(new MyForkJoinTask(0, 1000));

        System.out.println("result = " + result);

    }


    static class MyForkJoinTask extends RecursiveTask<Integer> {

        int begin, end;

        public MyForkJoinTask(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }

        @SneakyThrows
        @Override
        protected Integer compute() {
            if (begin == end) {
                log.debug("begin({}) == end({}), 结束递归!", begin, end);
                return begin;
            }
            if (end - 1 == begin) {
                log.debug("begin({}) == end - 1({} - 1), 结束递归!", begin, end);
                return begin + end;
            }
            // 分治
            int mid = (begin + end) / 2;
            MyForkJoinTask task1 = new MyForkJoinTask(begin, mid);
            MyForkJoinTask task2 = new MyForkJoinTask(mid + 1, end);
            log.debug("分治：{} ==> {} ==> {}", begin, mid, end);
            task1.fork();
            task2.fork();
            TimeUnit.MILLISECONDS.sleep(100);
            return task1.join() + task2.join();

        }
    }

}
